//
//  KCXunDianWenJuanController.swift
//  MyKC
//
//  Created by yy on 2017/3/29.
//  Copyright © 2017年 com.yasuo. All rights reserved.
import UIKit
import YYModel
import SVProgressHUD
import YYWebImage
class KCXunDianWenJuanController: UITableViewController {
    lazy var allDetailQusetionModelArray = [KCQuestionModel]()
    //根据type值来判断cell的id类型--------
    lazy var idDic = ["800001":"KCPatrolRepTipCellId","800002":"KCPatrolRepTipCellId","800003":"KCPatrolRepPhotoCellId","800004":"KCPatrolReasonCellId","800005":"KCPatrolInPutCellId"]
    //从上一个控制器点击传递进来的
    var model = KCPlanModel()
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        getData()
    }
}
// MARK: -  设置界面基本信息
extension KCXunDianWenJuanController {
    internal func setupUI() {
        //注册nib文件
        registerNib()
        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.estimatedRowHeight = 50
        tableView.tableFooterView = UIView()
        tableView.keyboardDismissMode = .onDrag
        title = "巡店反馈"
        //右侧提交按钮
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "提交", style: .plain, target: self, action: #selector(uploadData))
    }
    private func registerNib() {
        tableView.register(UINib(nibName: "KCPatrolRepHeadCell", bundle: nil), forCellReuseIdentifier: "KCPatrolRepHeadCellId")
        tableView.register(UINib(nibName: "KCPatrolRepTipCell", bundle: nil), forCellReuseIdentifier: "KCPatrolRepTipCellId")
        tableView.register(UINib(nibName: "KCPatrolRepPhotoCell", bundle: nil), forCellReuseIdentifier: "KCPatrolRepPhotoCellId")
        tableView.register(UINib(nibName: "KCPatrolReasonCell", bundle: nil), forCellReuseIdentifier: "KCPatrolReasonCellId")
        tableView.register(UINib(nibName: "KCPatrolInPutCell", bundle: nil), forCellReuseIdentifier: "KCPatrolInPutCellId")
        tableView.register(UINib(nibName: "KCPatrolRepDateCell", bundle: nil), forCellReuseIdentifier: "KCPatrolRepDateCellId")
    }
}
// MARK: -  数据源和代理方法
extension KCXunDianWenJuanController
{
    override func numberOfSections(in tableView: UITableView) -> Int {
        return self.allDetailQusetionModelArray.count
    }
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let model = self.allDetailQusetionModelArray[section]
//        model.QuestionType! 800001  如果是单选或者多选就根据行数来返回--其余的返回一行
        return (model.QuestionType! == "800001" || model.QuestionType! == "800002") ? model.questionCount + 1 : 2
    }
    // MARK: -  返回每行内容
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let identifier = getIdentifier(indexPath: indexPath)
        let cell = tableView.dequeueReusableCell(withIdentifier: identifier, for: indexPath)
        setupCell(cell: cell, indexPath: indexPath)
        return cell
    }
    private func getIdentifier(indexPath: IndexPath) -> String {
        let model = self.allDetailQusetionModelArray[indexPath.section]
        if indexPath.row == 0 {
            return "KCPatrolRepHeadCellId"
        }
        //走到下面说明不是第一行了------
        if model.KeyboardType! == "100023"{
            return "KCPatrolRepDateCellId"
        }
        return idDic[model.QuestionType!]!
    }
    // MARK: -  设置cell的内容
    private func setupCell(cell: UITableViewCell,indexPath: IndexPath) {
        let model = self.allDetailQusetionModelArray[indexPath.section]
        if indexPath.row == 0 {
            let cellHead = cell as! KCPatrolRepHeadCell
            cellHead.indexPath = indexPath
            cellHead.questionModel = model
        }
        else {
            if model.QuestionType! == "800001" || model.QuestionType! == "800002" {
                let cellTip = cell as! KCPatrolRepTipCell
                cellTip.indexPath = indexPath
                cellTip.questionModel = model
                cellTip.delegate = self
            }
            if model.QuestionType! == "800003"{
                let cellPhoto = cell as! KCPatrolRepPhotoCell
                cellPhoto.index = indexPath
                cellPhoto.questionModel = model
                cellPhoto.delegate = self
            }
        }
    }
    // MARK: - 代理方法
    override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 10
    }
}

// MARK: -  问题tipCell的里面选择按钮的代理方法
extension KCXunDianWenJuanController:KCPatrolRepTipCellDelegate {
    func repTipCellDidSelect(indexPath: IndexPath) {
        let indexSet = IndexSet.init(integer: indexPath.section)
        tableView.reloadSections(indexSet, with: .none)
    }
}

// MARK: -  点击相机按钮后的点击事件--------
extension KCXunDianWenJuanController:KCPatrolRepPhotoCellDelegate {
    //点击了某一个组的   里面collectionView里面的item
    func photoItemDidClick(item: NSInteger, indexPath: IndexPath) {
        let model = self.allDetailQusetionModelArray[indexPath.section]
        //给里面的图片和url数组进行增加
        //进入图片浏览页面
        if model.urlChangeImageArray == nil {
            model.urlChangeImageArray = [UIImage]()
        }
        if model.imageArray == nil {
            model.imageArray = [UIImage]()
        }
        
        if item == 0 {
            //判断
            if model.Array!.count + model.imageArray!.count < 5 {
                showAlert(model: model, indexPath: indexPath)
            }else {
                SVProgressHUD.showError(withStatus: "最多只能添加五张照片")
            }
        }
        else {
            for urlString in model.Array! {
                if let image = YYImageCache.shared().getImageForKey(urlString) {
                    model.urlChangeImageArray?.append(image)
                }
            }
            let allImageArray = model.urlChangeImageArray! + model.imageArray!
            let nsImageArray = NSMutableArray()
            for image in allImageArray {
                nsImageArray.add(image)
            }
            PhotoBaseManager.photoBaseShareManage().tapBrowser(item - 1, imageMutableArray: nsImageArray, viewController: self)
            
            //删除按钮的方法--------------
            PhotoBaseManager.photoBaseShareManage().deletPicture = {[weak self] selIndex -> Void in
                if item < model.Array!.count {
                    model.Array?.remove(at: selIndex)
                    model.urlChangeImageArray?.remove(at: selIndex)
                }
                else {
                    model.imageArray?.remove(at: selIndex - model.Array!.count)
                }
                let indexSet = IndexSet.init(integer: indexPath.section)
                self?.tableView.reloadSections(indexSet, with: .none)
            }
        }
    }
    
    // MARK: -  弹出窗口
    private func showAlert(model: KCQuestionModel,indexPath: IndexPath) {
        //打开相机或者图片浏览器
        //给出弹窗-----
        let alertC = UIAlertController(title: "温馨提示", message: "请选择相机或者照片", preferredStyle: .actionSheet)
        let caramerActionSure = UIAlertAction(title: "相机", style: .default, handler: { (sureAction) in
            PhotoBaseManager.photoBaseShareManage().getPhotoPicture(self, type: 0)
        })
        let photoActionSure = UIAlertAction(title: "照片", style: .default, handler: { (sureAction) in
            PhotoBaseManager.photoBaseShareManage().getPhotoPicture(self, type: 1)
        })
        
        PhotoBaseManager.photoBaseShareManage().getPhotoImage = { [weak self] imageData -> Void in
            if (imageData != nil) {
                self?.dismiss(animated: true, completion: nil)
                if let image = UIImage(data: imageData!) {
                    model.imageArray?.append(image)
                    let indexSet = IndexSet.init(integer: indexPath.section)
                    self?.tableView.reloadSections(indexSet, with: .none)
                }
            }
        }
        let actionCancel = UIAlertAction(title: "取消", style: .cancel, handler: nil)
        alertC.addAction(caramerActionSure)
        alertC.addAction(photoActionSure)
        alertC.addAction(actionCancel)
        present(alertC, animated: true, completion: nil)
    }
}

// MARK: -  获取网络数据-----
extension KCXunDianWenJuanController {
    internal func getData() {
        //这个方法在我写的时候只有我和上帝知道它有什么用
        let paraDic = ["TaskPlanId":model.TaskPlanId,"ModelTypeCode":"300001"]
        KCNetworkManager.sharedTools.request(method: .GET, urlString: "/api/FeedBack/GetFeedBack", parameters: paraDic) {[weak self] (response, error) in
            guard let response = response as? NSDictionary,let responseContent = response["Content"] as? NSDictionary,let responseQuestionDetail = responseContent["QuestionDetail"] as? NSArray else {
                return
            }
            //题目类型分为四种 单选 多选 拍照和 输入
            self?.allDetailQusetionModelArray = NSArray.yy_modelArray(with: KCQuestionModel.self, json: responseQuestionDetail) as? [KCQuestionModel] ?? [KCQuestionModel]()
            for detailModel in (self?.allDetailQusetionModelArray)! {
                detailModel.questionCount = (self?.getQuestionCount(model: detailModel))!
                if detailModel.Array == nil {
                    detailModel.Array = [String]()
                }
                if detailModel.imageArray == nil {
                    detailModel.imageArray = [UIImage]()
                }
            }
            self?.tableView.reloadData()
        }
    }
    private func getQuestionCount(model: KCQuestionModel) -> Int {
        if model.F?.characters.count != 0 {
            return 6
        }
        if model.E?.characters.count != 0 {
            return 5
        }
        if model.D?.characters.count != 0 {
            return 4
        }
        if model.C?.characters.count != 0 {
            return 3
        }
        if model.B?.characters.count != 0 {
            return 2
        }
        if model.A?.characters.count != 0 {
            return 1
        }
        return 0
    }
}

// MARK: -  提交网络数据------
extension KCXunDianWenJuanController {
    internal func uploadData() {
        if isNessaryTianXie() == false {
            return
        }
        var tmp = [[String: Any]]()
        //构造需要上传的参数-----------//-------------name是服务器接收图片的名字-----
        for detailQuestionModel in allDetailQusetionModelArray {
            var answer = ""
            var photoId = ""
            //单选
            if detailQuestionModel.QuestionType == "800001" {
                answer = detailQuestionModel.Array?.first ?? ""
            }
            //多选
            if detailQuestionModel.QuestionType == "800002" {
                let ansArray = detailQuestionModel.Array! as NSArray
                answer = ansArray.componentsJoined(by: ";")
            }
            //照片 提交照片
            if detailQuestionModel.QuestionType == "800003" {
                let ansArray = detailQuestionModel.Array! as NSArray
                photoId = ansArray.componentsJoined(by: ";")
            }
            let nessaryStr = detailQuestionModel.Necessary! as NSString
            
            let paraDic = ["QuestionId":detailQuestionModel.QuestionId,
                           "QuestionContent":detailQuestionModel.content,
                           "QuestionType":detailQuestionModel.QuestionType,
                           "Answer":answer,
                           "PhotosId":photoId,
                           "Photos":"",
                           "Necessary":"\(nessaryStr.integerValue)"]
            tmp.append(paraDic as [String : Any])
        }
        
        //记住什么时候把数组转换为字符串--------如果是多个东西要提交的时候,先把每个转为字典  然后在转为字符串-----------
        //如果是多张图片的话  一般会转为分号间隔的-------
        let tmpArray = tmp as NSArray
        let enumDicChangeStr = tmpArray.yy_modelToJSONString()
        var dic = [String: Any]()
        dic["StoreId"] = model.StoreId
        dic["TaskPlanId"] = model.TaskPlanId
        dic["ModelTypeCode"] = "300001"
        dic["FeedBackDetailString"] = enumDicChangeStr
        
        //上传网络图片-----------------------------
        KCNetworkManager.sharedTools.upload(urlString: "/api/FeedBack/PostFeedBack", parameters: dic, imageAllArray: allDetailQusetionModelArray) { (response, error) in
            
        }
    }
    private func isNessaryTianXie() -> Bool {
        //判断必选项是否没有完全填写
        var isTianXie = true
        for (index,questionModel) in allDetailQusetionModelArray.enumerated() {
            //如果是必选项-------
            if questionModel.Necessary == "1" {
                if questionModel.QuestionType == "800001" || questionModel.QuestionType == "800002" {
                    if questionModel.Array?.count == 0 {
                        isTianXie = false
                        SVProgressHUD.showError(withStatus:"第\(index)项是必选项")
                    }
                }
                if questionModel.QuestionType == "800004" || questionModel.QuestionType == "800005" {
                    if questionModel.Answer?.characters.count == 0 {
                        isTianXie = false
                        SVProgressHUD.showError(withStatus:"第\(index)项是必选项")
                    }
                }
                if questionModel.QuestionType == "800004"{
                    if questionModel.Array?.count == 0 && questionModel.imageArray?.count == 0 {
                        isTianXie = false
                        SVProgressHUD.showError(withStatus:"第\(index)项是必选项")
                    }
                }
            }
        }
        return isTianXie
    }
}
